package com.stool.cloud.api;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.stool.cloud.service.IProviderService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author Felix YF Dong
 * @Description
 * @Date 2023/2/10
 */
@RestController
@RequestMapping("/consumer")
public class ConsumerApi {

    @Value("${service-url.nacos-user-service}")
    private String serverURL;

    @Resource
    private RestTemplate restTemplate;

    @GetMapping(value = "/fallback/{id}")
//    @SentinelResource("fallback") // 没有配置
//    @SentinelResource(value = "fallback", fallback = "handlerFallback") // 负责业务异常
//    @SentinelResource(value = "fallback", blockHandler = "blockHandler") // blockHandler负责sentinel控制台配置违规
    @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler", exceptionsToIgnore = {IllegalArgumentException.class}) // blockHandler
    public String paymentInfo(@PathVariable("id") String id)
    {

        String result = restTemplate.getForObject(serverURL + "/provider/" + id, String.class);
        if ("3".equals(id)) {
            throw new IllegalArgumentException("IllegalArgumentException, 非参参数异常....");
        } else if (!result.contains(id)) {
            throw new NullPointerException("NullPointerException, 没有记录");
        }
        return result;
    }

    public String handlerFallback(@PathVariable String id, Throwable e) {
        return "id是" + id + "***兜底异常，内容" + e.getMessage();
    }

    public String blockHandler(@PathVariable String id, BlockException blockException) {

        return "id是" + id + "***blockHandler-sentinel限流，内容" + blockException.getMessage();
    }

    @Resource
    private IProviderService providerService;

    @GetMapping(value = "/fallback1/{id}")
    public String paymentInfo1(@PathVariable("id") String id)
    {

        return providerService.providerQL(id);
    }

}
